<template>
  <view class="ad-video-container">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="back-btn" @tap="handleBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-title">观看广告解锁WiFi</view>
    </view>
    
    <!-- 主内容区域 -->
    <view class="content-area">
      <!-- WiFi信息展示 -->
      <view class="wifi-info-card">
        <view class="wifi-icon">📶</view>
        <view class="wifi-name">{{ wifiInfo.ssid || '未知WiFi' }}</view>
        <view class="wifi-tip">请观看完整广告即可免费连接</view>
      </view>
      
      <!-- 步骤指引 -->
      <view class="steps-area">
        <view class="step-item" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
          <view class="step-number">1</view>
          <view class="step-text">观看广告</view>
        </view>
        <view class="step-line"></view>
        <view class="step-item" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
          <view class="step-number">2</view>
          <view class="step-text">连接WiFi</view>
        </view>
        <view class="step-line"></view>
        <view class="step-item" :class="{ active: currentStep >= 3, completed: currentStep > 3 }">
          <view class="step-number">3</view>
          <view class="step-text">完成认证</view>
        </view>
      </view>
      
      <!-- 广告加载状态 -->
      <view class="ad-status-area" v-if="!adPlaying">
        <view class="status-icon">{{ adLoaded ? '✅' : '⏳' }}</view>
        <view class="status-text">{{ adStatusText }}</view>
      </view>
      
      <!-- 播放广告按钮 -->
      <view class="action-area">
        <button 
          class="play-ad-btn" 
          @tap="showRewardedVideoAd"
          :disabled="!adLoaded || processing"
        >
          {{ buttonText }}
        </button>
      </view>
      
      <!-- 提示信息 -->
      <view class="tips-area">
        <view class="tip-item">💡 广告时长约15-30秒</view>
        <view class="tip-item">💡 观看完整广告即可免费上网</view>
        <view class="tip-item">💡 不消耗您的流量</view>
      </view>
    </view>
  </view>
</template>

<script>
// 不再需要调用认证接口，路由器会自动处理

export default {
  name: 'AdVideo',
  data() {
    return {
      deviceId: '',
      wifiInfo: {},
      currentStep: 1, // 当前步骤：1-观看广告，2-连接WiFi，3-完成认证
      rewardedVideoAd: null,
      adLoaded: false,
      adPlaying: false,
      processing: false,
      isIOS: false,
      adWatchCompleted: false // 广告是否已观看完成（标志位）
    }
  },
  computed: {
    adStatusText() {
      if (this.adLoaded) {
        return '广告已就绪，点击下方按钮开始播放'
      } else {
        return '广告加载中，请稍候...'
      }
    },
    buttonText() {
      if (this.processing) {
        return '处理中...'
      }
      if (this.adPlaying) {
        return '广告播放中...'
      }
      if (this.adLoaded) {
        return '开始播放广告'
      }
      return '广告加载中...'
    }
  },
  onLoad(options) {
    console.log('广告页面参数：', options)
    
    // 获取参数
    this.deviceId = options.deviceId || ''
    
    // 解析WiFi信息（从URL参数传递）
    if (options.wifiInfo) {
      try {
        this.wifiInfo = JSON.parse(decodeURIComponent(options.wifiInfo))
        console.log('WiFi信息：', this.wifiInfo)
      } catch (e) {
        console.error('解析WiFi信息失败：', e)
        this.wifiInfo = { ssid: options.ssid || '未知WiFi' }
      }
    }
    
    // 检测系统平台
    const systemInfo = uni.getSystemInfoSync()
    this.isIOS = systemInfo.platform === 'ios'
    
    // 初始化WiFi模块
    this.initWifiModule()
    
    // 初始化激励视频广告
    this.initRewardedVideoAd()
  },
  onUnload() {
    // 销毁广告实例
    if (this.rewardedVideoAd) {
      this.rewardedVideoAd.destroy()
      this.rewardedVideoAd = null
    }
    
    // 关闭WiFi模块
    uni.stopWifi({
      success: () => {
        console.log('WiFi模块已关闭')
      }
    })
  },
  methods: {
    // 返回上一页
    handleBack() {
      if (this.processing) {
        uni.showModal({
          title: '提示',
          content: '正在处理中，确定要返回吗？',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack()
            }
          }
        })
      } else {
        uni.navigateBack()
      }
    },
    
    // 初始化WiFi模块
    initWifiModule() {
      uni.startWifi({
        success: () => {
          console.log('WiFi模块初始化成功')
          
          // 监听WiFi连接成功
          this.onWifiConnectedHandler = (res) => {
            console.log('监听到WiFi连接成功：', res)
            
            // 只有在广告观看完成后，才处理WiFi连接成功事件
            if (!this.adWatchCompleted) {
              console.log('广告尚未观看完成，忽略WiFi连接事件')
              return
            }
            
            if (this.wifiInfo.ssid && res.wifi && res.wifi.SSID) {
              if (res.wifi.SSID.toLowerCase() === this.wifiInfo.ssid.toLowerCase()) {
                console.log('成功连接到目标WiFi：', res.wifi.SSID)
                this.handleWifiConnectSuccess()
              }
            }
          }
          
          uni.onWifiConnected(this.onWifiConnectedHandler)
        },
        fail: (error) => {
          console.error('WiFi模块初始化失败：', error)
        }
      })
    },
    
    // 初始化激励视频广告
    initRewardedVideoAd() {
      if (!wx.createRewardedVideoAd) {
        console.warn('当前微信版本不支持激励视频广告')
        uni.showModal({
          title: '提示',
          content: '当前微信版本不支持激励视频广告，请升级微信版本',
          showCancel: false
        })
        return
      }
      
      try {
        // 创建激励视频广告实例
        this.rewardedVideoAd = wx.createRewardedVideoAd({
          adUnitId: 'adunit-fe47c80bf8b283e2'
        })
        
        // 监听广告加载成功
        this.rewardedVideoAd.onLoad(() => {
          console.log('激励视频广告加载成功')
          this.adLoaded = true
        })
        
        // 监听广告加载失败
        this.rewardedVideoAd.onError((err) => {
          console.error('激励视频广告加载失败：', err)
          this.adLoaded = false
          
          uni.showToast({
            title: '广告加载失败，请稍后重试',
            icon: 'none'
          })
        })
        
        // 监听广告关闭
        this.rewardedVideoAd.onClose((res) => {
          console.log('激励视频广告关闭：', res)
          this.adPlaying = false
          
          if (res && res.isEnded) {
            // 用户完整观看了广告
            console.log('用户完整观看了广告')
            this.handleAdWatchCompleted()
          } else {
            // 用户中途关闭了广告
            console.log('用户未完整观看广告')
            this.adWatchCompleted = false // 重置标志位
            uni.showModal({
              title: '提示',
              content: '需要观看完整广告才能免费使用WiFi哦',
              showCancel: false,
              confirmText: '我知道了'
            })
            this.currentStep = 1
          }
        })
        
        console.log('激励视频广告初始化完成')
      } catch (error) {
        console.error('初始化激励视频广告失败：', error)
      }
    },
    
    // 显示激励视频广告
    async showRewardedVideoAd() {
      if (!this.rewardedVideoAd) {
        uni.showToast({
          title: '广告未初始化',
          icon: 'none'
        })
        return
      }
      
      if (!this.adLoaded) {
        uni.showToast({
          title: '广告加载中，请稍候',
          icon: 'none'
        })
        return
      }
      
      try {
        console.log('准备播放激励视频广告')
        this.adPlaying = true
        
        // 显示广告
        try {
          await this.rewardedVideoAd.show()
          console.log('激励视频广告显示成功')
        } catch (showError) {
          console.error('显示广告失败，尝试重新加载：', showError)
          
          // 如果显示失败，尝试重新加载
          await this.rewardedVideoAd.load()
          await this.rewardedVideoAd.show()
          console.log('重新加载后显示成功')
        }
      } catch (error) {
        console.error('显示激励视频广告失败：', error)
        this.adPlaying = false
        
        uni.showModal({
          title: '广告加载失败',
          content: '暂时无法加载广告，请稍后重试',
          confirmText: '重试',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              // 重新初始化广告
              this.adLoaded = false
              this.initRewardedVideoAd()
            }
          }
        })
      }
    },
    
    // 广告观看完成后的处理
    async handleAdWatchCompleted() {
      try {
        console.log('广告观看完成，进入步骤2：连接WiFi')
        this.currentStep = 2
        this.processing = true
        this.adWatchCompleted = true // 标记广告已观看完成
        
        uni.showLoading({ title: '正在连接WiFi...' })
        
        // 先检查是否已经连接到目标WiFi
        const isAlreadyConnected = await this.checkWifiConnection(this.wifiInfo.ssid)
        
        if (isAlreadyConnected) {
          console.log('用户已连接到目标WiFi')
          await this.handleWifiConnectSuccess()
          return
        }
        
        // 尝试自动连接WiFi
        try {
          await this.connectToWifi(this.wifiInfo.ssid, this.wifiInfo.password)
          console.log('WiFi连接API调用成功，等待连接...')
          
          // 设置超时检查
          setTimeout(async () => {
            if (this.processing && this.currentStep === 2) {
              console.log('10秒超时，检查连接状态...')
              const recheckConnected = await this.checkWifiConnection(this.wifiInfo.ssid)
              
              if (recheckConnected) {
                console.log('超时检查：实际已连接')
                await this.handleWifiConnectSuccess()
              } else {
                this.showManualConnectTip()
              }
            }
          }, 10000)
          
        } catch (connectError) {
          console.error('WiFi连接失败：', connectError)
          
          // 等待3秒后再次检查
          await new Promise(resolve => setTimeout(resolve, 3000))
          const recheckConnected = await this.checkWifiConnection(this.wifiInfo.ssid)
          
          if (recheckConnected) {
            console.log('虽然API返回失败，但实际已连接')
            await this.handleWifiConnectSuccess()
          } else {
            this.showManualConnectTip()
          }
        }
        
      } catch (error) {
        console.error('处理广告完成失败：', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '处理失败',
          icon: 'error'
        })
        this.processing = false
        this.currentStep = 1
        this.adWatchCompleted = false // 重置标志位
      }
    },
    
    // WiFi连接成功处理
    async handleWifiConnectSuccess() {
      try {
        console.log('WiFi连接成功，进入步骤3：完成认证')
        this.currentStep = 3
        
        uni.hideLoading()
        
        // WiFi连接成功后，路由器会自动轮询认证接口
        // 路由器会使用真实的MAC地址进行认证，无需小程序调用接口
        console.log('WiFi已连接，路由器将自动进行认证...')
        
        // 等待1秒让路由器有时间处理认证
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 认证成功提示
        uni.showModal({
          title: '认证成功 🎉',
          content: '您已成功连接WiFi，可以开始上网了！\n\n路由器正在为您开通网络访问权限...',
          showCancel: false,
          confirmText: '开始上网',
          success: () => {
            this.processing = false
            // 返回首页
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/index'
              })
            }, 300)
          }
        })
        
      } catch (error) {
        console.error('WiFi连接成功处理失败：', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '处理失败',
          icon: 'error'
        })
        this.processing = false
        this.currentStep = 2
        this.adWatchCompleted = false // 重置标志位，允许重新观看广告
      }
    },
    
    // 显示手动连接提示
    showManualConnectTip() {
      uni.hideLoading()
      
      const errorMsg = this.isIOS 
        ? `自动连接失败。iOS系统需要iOS 11及以上版本才能自动连接WiFi。\n\nWiFi名称：${this.wifiInfo.ssid}\n密码：${this.wifiInfo.password}\n\n请手动连接WiFi后点击"继续"。`
        : `自动连接失败。\n\nWiFi名称：${this.wifiInfo.ssid}\n密码：${this.wifiInfo.password}\n\n请手动连接WiFi后点击"继续"。`
      
      uni.showModal({
        title: '需要手动连接',
        content: errorMsg,
        confirmText: '复制密码',
        cancelText: '继续',
        success: async (res) => {
          if (res.confirm) {
            // 复制密码
            uni.setClipboardData({
              data: this.wifiInfo.password,
              success: () => {
                uni.showToast({
                  title: '密码已复制',
                  icon: 'success'
                })
                setTimeout(() => this.showManualConnectTip(), 500)
              }
            })
          } else {
            // 用户点击继续，检查连接状态
            const recheckConnected = await this.checkWifiConnection(this.wifiInfo.ssid)
            
            if (recheckConnected) {
              await this.handleWifiConnectSuccess()
            } else {
              uni.showToast({
                title: '请先连接WiFi',
                icon: 'none'
              })
              this.processing = false
              this.currentStep = 2
              this.adWatchCompleted = false // 重置标志位
            }
          }
        }
      })
    },
    
    // 检查WiFi连接状态
    async checkWifiConnection(targetSSID) {
      try {
        const wifiInfo = await this.getConnectedWifiInfo()
        
        if (wifiInfo && wifiInfo.SSID) {
          return wifiInfo.SSID.toLowerCase() === targetSSID.toLowerCase()
        }
        
        return false
      } catch (error) {
        console.error('检查WiFi连接状态失败：', error)
        return false
      }
    },
    
    // 获取已连接的WiFi信息
    getConnectedWifiInfo() {
      return new Promise((resolve, reject) => {
        uni.getConnectedWifi({
          success: (res) => {
            resolve(res.wifi)
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    },
    
    // 连接WiFi
    connectToWifi(ssid, password) {
      return new Promise((resolve, reject) => {
        console.log(`开始连接WiFi - SSID: ${ssid}`)
        
        uni.connectWifi({
          SSID: ssid,
          password: password,
          success: (res) => {
            console.log('connectWifi API返回成功：', res)
            resolve(res)
          },
          fail: (error) => {
            console.error('connectWifi API调用失败：', error)
            reject(error)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ad-video-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

.nav-bar {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60rpx 40rpx 20rpx;
  color: #fff;
}

.back-btn {
  position: absolute;
  left: 40rpx;
  top: 60rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
}

.back-icon {
  font-size: 36rpx;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
}

.content-area {
  padding: 40rpx;
}

.wifi-info-card {
  background: #fff;
  border-radius: 40rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  margin-bottom: 60rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.wifi-icon {
  font-size: 100rpx;
  margin-bottom: 20rpx;
}

.wifi-name {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.wifi-tip {
  font-size: 28rpx;
  color: #666;
}

.steps-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 80rpx;
  padding: 0 20rpx;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 0 0 auto;
}

.step-number {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
  transition: all 0.3s;
}

.step-item.active .step-number {
  background: #fff;
  color: #667eea;
  transform: scale(1.1);
}

.step-item.completed .step-number {
  background: #52c41a;
  color: #fff;
}

.step-text {
  font-size: 24rpx;
  color: #fff;
  opacity: 0.8;
}

.step-item.active .step-text {
  opacity: 1;
  font-weight: bold;
}

.step-line {
  flex: 1;
  height: 4rpx;
  background: rgba(255, 255, 255, 0.3);
  margin: 0 20rpx;
  margin-bottom: 36rpx;
}

.ad-status-area {
  text-align: center;
  margin-bottom: 60rpx;
  padding: 40rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 30rpx;
}

.status-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.status-text {
  font-size: 28rpx;
  color: #fff;
  line-height: 1.6;
}

.action-area {
  margin-bottom: 60rpx;
}

.play-ad-btn {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, #ff9a00 0%, #ff6b00 100%);
  border: none;
  border-radius: 50rpx;
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  box-shadow: 0 6rpx 20rpx rgba(255, 107, 0, 0.4);
  
  &::after {
    border: none;
  }
  
  &:disabled {
    opacity: 0.6;
    background: #ccc;
    box-shadow: none;
  }
}

.tips-area {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 30rpx;
  padding: 40rpx;
}

.tip-item {
  font-size: 26rpx;
  color: #fff;
  line-height: 2;
  opacity: 0.9;
}
</style>

